/**
 *
 */
package com.sinopec.siam.provisioning.handle;

import com.cloudstore.dev.api.util.MD5;
import com.sinopec.siam.apache.log4j.Logger;
import com.sinopec.siam.provisioning.entity.*;
import com.sinopec.siam.provisioning.listener.ProvisioningEventListener;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

/**
 * 默认监听事件处理实现类<br>
 * 接口默认将事件XML转换成ProvisioningEvent对象。
 *
 * @author zhaodonglu
 * @since 2012-7-23 下午2:00:17
 */
public class SimpleProvisioningEventListener implements ProvisioningEventListener {

    private static Logger log = Logger.getLogger(SimpleProvisioningEventListener.class);

    /**
     *
     */
    public SimpleProvisioningEventListener() {
        super();
    }

    public void process(ProvisioningEvents events) {

        List<ProvisioningEvent> list = events.getEvent();
        log.info("list.size===================" + list.size());
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        System.out.println("list.size===================" + list.size());
        for (int i = 0; i < list.size(); i++) {
            ProvisioningEvent event = new ProvisioningEvent();
            event = list.get(i);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(event.getOccuredTimestamp().getTime());
            log.info("监听到事件内容如下:");
            log.info("事件流水号:" + event.getEventId());
            if (event.getOccuredTimestamp() == null) {
                log.info("事件发生时间:null");
            } else {
                log.info("事件发生时间:" + time);
            }
            log.info("事件类型:" + event.getEventType());

            /**
             * 应用账号创建
             */
            if (EventType.ACCOUNT_CREATED.equals(event.getEventType())) {
                log.info("---------- 应用账号创建开始 ------------");

                String account_uid = "";//应用账号
                String uid = "";//用户账号
                String app_name = "";//应用名称
                String cn = "";//姓名
                String spgender = ""; //性别 1:男 2:女
                String employeenumber = "";//员工编码
                String CorpemployeeNumber = ""; //企业员工编码
                String ou = "";//部门名称
                String sporgnumber = ""; //直属单位编码
                String departmentnumber = ""; //所属部门编码
                String sporgnamepath = ""; //机构名 path
                String sporgcodepath = ""; //机构 codePath
                String mail = ""; //自设邮箱
                String mobile = ""; //手机号码
                String spemployeelevel = ""; //职位序列层级
                String spentrystatus = ""; //账号状态
                String spnation = ""; //民族
                String c = ""; //国家代码
                String spupdatedate = ""; //最后更新时间
                String spemployeesubtype = ""; //员工子类型
                String sppositionstatus = ""; //岗位状态
                String employeetype = ""; //员工类型
                String usertype = ""; //员工类型
                String spcountry = ""; //国籍
                String telephonenumber = ""; // 工作电话
                String sppositionname = ""; //岗位名称
                String sppositionnumber = ""; //岗位编号
                String sptitlelevel = ""; //主要职务级别
                String sppluralitytitles = ""; //兼任职务名称
                String sptitlenumber = ""; //职务编码
                String sptitlecategory = ""; //职务分类

                String regex = "^/*|/*$";
                TargetEntity applicationEntity = event.getApplication();
                if (applicationEntity != null) {
                    TargetSubject applicationSubject = applicationEntity.getSubject();
                    app_name = applicationSubject.getSubject();
                    log.info("应用系统:" + app_name);
                }

                TargetEntity personEntity = event.getPerson();
                if (personEntity != null) {
                    TargetSubject personSubject = personEntity.getSubject();
                    uid = personSubject.getSubject();
                    log.info("用户账号:" + uid);
                }

                TargetEntity targetEntity = event.getTargetEntity();
                if (targetEntity != null) {
                    TargetSubject targetSubject = targetEntity.getSubject();
                    account_uid = targetSubject.getSubject();
                    log.info("应用账号:" + account_uid);
                    log.info("应用账号属性集合:");
                    List<Attribute> attributes = targetEntity.getAttributes();
                    for (Attribute attribute : attributes) {
                        if (attribute.getName().equals("cn")) {
                            cn = (String) attribute.getValues().get(0);
                            log.info("姓名:" + cn);
                        }
                        if (attribute.getName().equals("spgender")) {
                            spgender = (String) attribute.getValues().get(0);
                            log.info("性别:" + spgender);
                        }
                        if (attribute.getName().equals("employeenumber")) {
                            employeenumber = (String) attribute.getValues().get(0);
                            log.info("员工编码:" + employeenumber);
                        }
                        if (attribute.getName().equals("CorpemployeeNumber")) {
                            CorpemployeeNumber = (String) attribute.getValues().get(0);
                            log.info("企业员工编码:" + CorpemployeeNumber);
                        }
                        if (attribute.getName().equals("ou")) {
                            ou = (String) attribute.getValues().get(0);
                            log.info("部门名称:" + ou);
                        }
                        if (attribute.getName().equals("sporgnumber")) {
                            sporgnumber = (String) attribute.getValues().get(0);
                            log.info("直属单位编码:" + sporgnumber);
                        }
                        if (attribute.getName().equals("departmentnumber")) {
                            departmentnumber = (String) attribute.getValues().get(0);
                            log.info("所属部门编码:" + departmentnumber);
                        }
                        if (attribute.getName().equals("sporgnamepath")) {
                            sporgnamepath = (String) attribute.getValues().get(0);
                            log.info("机构名 path:" + sporgnamepath);
                        }
                        if (attribute.getName().equals("sporgcodepath")) {
                            sporgcodepath = (String) attribute.getValues().get(0);
                            log.info("机构 codePath:" + sporgcodepath);
                        }
                        if (attribute.getName().equals("mail")) {
                            mail = (String) attribute.getValues().get(0);
                            log.info("自设邮箱:" + mail);
                        }
                        if (attribute.getName().equals("mobile")) {
                            mobile = (String) attribute.getValues().get(0);
                            log.info("手机号码:" + mobile);
                        }
                        if (attribute.getName().equals("spemployeelevel")) {
                            spemployeelevel = (String) attribute.getValues().get(0);
                            log.info("职位序列层级:" + spemployeelevel);
                        }
                        if (attribute.getName().equals("spentrystatus")) {
                            spentrystatus = (String) attribute.getValues().get(0);
                            log.info("账号状态:" + spentrystatus);
                        }
                        if (attribute.getName().equals("spnation")) {
                            spnation = (String) attribute.getValues().get(0);
                            log.info("民族:" + spnation);
                        }
                        if (attribute.getName().equals("c")) {
                            c = (String) attribute.getValues().get(0);
                            log.info("国家代码:" + c);
                        }
                        if (attribute.getName().equals("spupdatedate")) {
                            spupdatedate = (String) attribute.getValues().get(0);
                            log.info("最后更新时间:" + spupdatedate);
                        }
                        if (attribute.getName().equals("spemployeesubtype")) {
                            spemployeesubtype = (String) attribute.getValues().get(0);
                            log.info("员工子类型:" + spemployeesubtype);
                        }
                        if (attribute.getName().equals("sppositionstatus")) {
                            sppositionstatus = (String) attribute.getValues().get(0);
                            log.info("岗位状态:" + sppositionstatus);
                        }
                        if (attribute.getName().equals("employeetype")) {
                            employeetype = (String) attribute.getValues().get(0);
                            log.info("员工类型:" + employeetype);
                        }
                        if (attribute.getName().equals("usertype")) {
                            usertype = (String) attribute.getValues().get(0);
                            log.info("员工类型:" + usertype);
                        }
                        if (attribute.getName().equals("spcountry")) {
                            spcountry = (String) attribute.getValues().get(0);
                            log.info("国籍:" + spcountry);
                        }
                        if (attribute.getName().equals("telephonenumber")) {
                            telephonenumber = (String) attribute.getValues().get(0);
                            log.info("工作电话:" + telephonenumber);
                        }
                        if (attribute.getName().equals("sppositionname")) {
                            sppositionname = (String) attribute.getValues().get(0);
                            log.info("岗位名称:" + sppositionname);
                        }
                        if (attribute.getName().equals("sppositionnumber")) {
                            sppositionnumber = (String) attribute.getValues().get(0);
                            log.info("岗位编号:" + sppositionnumber);
                        }
                        if (attribute.getName().equals("sptitlelevel")) {
                            sptitlelevel = (String) attribute.getValues().get(0);
                            log.info("主要职务级别:" + sptitlelevel);
                        }
                        if (attribute.getName().equals("sppluralitytitles")) {
                            sppluralitytitles = (String) attribute.getValues().get(0);
                            log.info("兼任职务名称:" + sppluralitytitles);
                        }
                        if (attribute.getName().equals("sptitlenumber")) {
                            sptitlenumber = (String) attribute.getValues().get(0);
                            log.info("职务编码:" + sptitlenumber);
                        }
                        if (attribute.getName().equals("sptitlecategory")) {
                            sptitlecategory = (String) attribute.getValues().get(0);
                            log.info("职务分类:" + sptitlecategory);
                        }
                    }
                    // log.info(attribute);
                    // 其他属性取值，自己编写代码
                    int departmentid = 308; //所属部门id
                    int userid = getMaxHrmResourceId();
                    int subcompanyid = 48; //所属分部id
                    String password = MD5.md5("Aa123456").toUpperCase();
                    String date = time.substring(0, 10);
                    int sex = "1".equals(spgender) ? 0 : 1;//性别 0:男 1:女
                    int seclevel = 0;
                    //人员信息
                    rs.execute("select id from HrmResource where loginid='" + account_uid + "'");
                    if (!rs.next()) {
                        UUID uuid = UUID.randomUUID();
                        String MODEUUID = uuid.toString().toUpperCase();
                        rs.execute("insert into HrmResource(id,loginid,password,lastname,sex,systemlanguage,maritalstatus,telephone,email,seclevel,departmentid,locationid," +
                                "subcompanyid1,createrid,createdate,lastmodid,lastmoddate,workcode,status,creater,created,modifier,modified,uuid) " +
                                "values('" + userid + "','" + account_uid + "','" + password + "','" + cn + "','" + sex + "','7','1','" + telephonenumber + "','" + mail + "'," + seclevel + "," + departmentid + ",2," +
                                "'" + subcompanyid + "','1','" + date + "','1','" + date + "','" + employeenumber + "','1','1',to_timestamp('" + time + "', 'yyyy-mm-dd hh24:mi:ss'),'1',to_timestamp('" + time + "', 'yyyy-mm-dd hh24:mi:ss'),'" + MODEUUID + "')");
                        log.info("insert into HrmResource(id,loginid,password,lastname,sex,systemlanguage,maritalstatus,telephone,email,seclevel,departmentid,locationid," +
                                "subcompanyid1,createrid,createdate,lastmodid,lastmoddate,workcode,status,creater,created,modifier,modified,uuid) " +
                                "values('" + userid + "','" + account_uid + "','" + password + "','" + cn + "','" + sex + "','7','1','" + telephonenumber + "','" + mail + "'," + seclevel + "," + departmentid + ",2," +
                                "'" + subcompanyid + "','1','" + date + "','1','" + date + "','" + employeenumber + "','1','1','" + time + "','1','" + time + "','" + MODEUUID + "')");
                        int resourceid = getBillidByUUID(MODEUUID, "HrmResource");
                        log.info("----------------- 人员数据库表信息增加成功 ----------------");
                        try {
                            ResourceComInfo rc = new ResourceComInfo();
                            rc.addResourceInfoCache(String.valueOf(resourceid));
                            log.info("================= 人员缓存信息增加成功 ================");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                log.info("---------- 应用账号创建结束 ------------");
            }
            /**
             * 应用账号修改
             */
            if (EventType.ACCOUNT_MODIFIED.equals(event.getEventType())) {
                log.info("---------- 应用账号修改开始 ------------");

                String account_uid = "";//应用账号
                String uid = "";//用户账号
                String app_name = "";//应用名称
                String cn = "";//姓名
                String ou = "";//部门
                String employeenumber = "";//员工编码

                TargetEntity applicationEntity = event.getApplication();
                if (applicationEntity != null) {
                    TargetSubject applicationSubject = applicationEntity.getSubject();
                    app_name = applicationSubject.getSubject();
                    log.info("应用系统:" + app_name);
                }

                TargetEntity personEntity = event.getPerson();
                if (personEntity != null) {
                    TargetSubject personSubject = personEntity.getSubject();
                    uid = personSubject.getSubject();
                    log.info("用户账号:" + uid);
                }
                TargetEntity targetEntity = event.getTargetEntity();
                if (targetEntity != null) {
                    TargetSubject targetSubject = targetEntity.getSubject();
                    account_uid = targetSubject.getSubject();
                    log.info("应用账号:" + account_uid);
                    log.info("应用账号属性集合:");
                    List<Attribute> attributes = targetEntity.getAttributes();
                    for (Attribute attribute : attributes) {
                        if (attribute.getName().equals("cn")) {
                            cn = (String) attribute.getValues().get(0);
                            log.info("姓名:" + cn);
                        }
                        if (attribute.getName().equals("employeenumber")) {
                            employeenumber = (String) attribute.getValues().get(0);
                            log.info("员工编码:" + employeenumber);
                        }
                        if (attribute.getName().equals("ou")) {
                            ou = (String) attribute.getValues().get(0);
                            log.info("部门:" + ou);
                        }
                    }
                    // log.info(attribute);
                    // 其他属性取值，自己编写代码
                }
                log.info("---------- 应用账号修改结束 ------------");
            }

            /**
             * 应用账号禁用
             */
            if (EventType.ACCOUNT_DISABLED.equals(event.getEventType())) {
                log.info("---------- 应用账号禁用开始 ------------");

                String account_uid = "";//应用账号
                String uid = "";//用户账号
                String app_name = "";//应用名称
                String cn = "";//姓名
                String ou = "";//部门

                TargetEntity applicationEntity = event.getApplication();
                if (applicationEntity != null) {
                    TargetSubject applicationSubject = applicationEntity.getSubject();
                    app_name = applicationSubject.getSubject();
                    log.info("应用系统:" + app_name);
                }

                TargetEntity personEntity = event.getPerson();
                if (personEntity != null) {
                    TargetSubject personSubject = personEntity.getSubject();
                    uid = personSubject.getSubject();
                    log.info("用户账号:" + uid);
                }
                TargetEntity targetEntity = event.getTargetEntity();
                if (targetEntity != null) {
                    TargetSubject targetSubject = targetEntity.getSubject();
                    account_uid = targetSubject.getSubject();
                    log.info("应用账号:" + account_uid);
                    List<Attribute> attributes = targetEntity.getAttributes();
                    for (Attribute attribute : attributes) {
                        if (attribute.getName().equals("cn")) {
                            cn = (String) attribute.getValues().get(0);
                            log.info("姓名:" + cn);
                        }
                        if (attribute.getName().equals("ou")) {
                            ou = (String) attribute.getValues().get(0);
                            log.info("部门名称:" + ou);
                        }
                    }
                }

                if (account_uid != null && !"".equals(account_uid)) {
                    rs.execute("select status from HrmResource where loginid='" + account_uid + "'");
                    if (rs.next()) {
                        String status = Util.null2String(rs.getString("status"));
                        if ("1".equals(status)) {
                            rs1.execute("update HrmResource set status='5' where loginid='" + account_uid + "'");
                        }
                    }

                }
                log.info("---------- 应用账号禁用结束 ------------");
            }
            /**
             * 应用账号启用
             */
            if (EventType.ACCOUNT_ENABLED.equals(event.getEventType())) {
                log.info("---------- 应用账号启用开始 ------------");

                String account_uid = "";//应用账号
                String uid = "";//用户账号
                String app_name = "";//应用名称

                TargetEntity applicationEntity = event.getApplication();
                if (applicationEntity != null) {
                    TargetSubject applicationSubject = applicationEntity.getSubject();
                    app_name = applicationSubject.getSubject();
                    log.info("应用系统:" + app_name);
                }
                TargetEntity personEntity = event.getPerson();
                if (personEntity != null) {
                    TargetSubject personSubject = personEntity.getSubject();
                    uid = personSubject.getSubject();
                    log.info("用户账号:" + uid);
                }
                TargetEntity targetEntity = event.getTargetEntity();
                if (targetEntity != null) {
                    TargetSubject targetSubject = targetEntity.getSubject();
                    account_uid = targetSubject.getSubject();
                    log.info("应用账号:" + account_uid);
                }

                if (account_uid != null && !"".equals(account_uid)) {
                    rs.execute("select status from HrmResource where loginid='" + account_uid + "'");
                    log.info("select status from HrmResource where loginid='" + account_uid + "'");
                    if (rs.next()) {
                        String status = Util.null2String(rs.getString("status"));
                        if ("5".equals(status)) {
                            rs1.execute("update HrmResource set status='1' where loginid='" + account_uid + "'");
                            log.info("update HrmResource set status='1' where loginid='" + account_uid + "'");
                        }
                    }

                }
                log.info("---------- 应用账号启用结束 ------------");
            }
            /**
             * 应用账号删除
             */
            if (EventType.ACCOUNT_DELETED.equals(event.getEventType())) {
                log.info("---------- 应用账号删除开始 ------------");

                String account_uid = "";//应用账号
                String uid = "";//用户账号
                String app_name = "";//应用名称

                TargetEntity applicationEntity = event.getApplication();
                if (applicationEntity != null) {
                    TargetSubject applicationSubject = applicationEntity.getSubject();
                    app_name = applicationSubject.getSubject();
                    log.info("应用系统:" + app_name);
                }
                TargetEntity personEntity = event.getPerson();
                if (personEntity != null) {
                    TargetSubject personSubject = personEntity.getSubject();
                    uid = personSubject.getSubject();
                    log.info("用户账号:" + uid);
                }
                TargetEntity targetEntity = event.getTargetEntity();
                if (targetEntity != null) {
                    TargetSubject targetSubject = targetEntity.getSubject();
                    account_uid = targetSubject.getSubject();
                    log.info("应用账号:" + account_uid);
                }

                if (account_uid != null && !"".equals(account_uid)) {
                    rs.execute("select status from HrmResource where loginid='" + account_uid + "'");
                    log.info("select status from HrmResource where loginid='" + account_uid + "'");
                    if (rs.next()) {
                        String status = Util.null2String(rs.getString("status"));
                        if ("5".equals(status)) {
                            rs1.execute("update HrmResource set status=5 where loginid='" + account_uid + "'");
                            log.info("update HrmResource set status=5 where loginid='" + account_uid + "'");
                        }
                    }

                }
                log.info("---------- 应用账号删除结束 ------------");
            }

        }
    }


    /**
     * 根据部门编码获取id，如果查不到 统一放到 临时部门 下
     * @param depcode
     * @return
     */
    public int getIdByCode(String depcode) {
        RecordSet rs = new RecordSet();
        int id = 1310;  //临时部门的id
        rs.execute("select id from HrmDepartment where departmentcode='" + depcode + "'");
        if (rs.next()) {
            id = Util.getIntValue(rs.getString("id"));
        }
        return id;
    }

    /**
     * 根据获取人力资源表最大ID
     * @return
     */
    public int getMaxHrmResourceId() {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select max(id) from HrmResource");
        rs.next();
        int id = Util.getIntValue(rs.getString(1), 0);
        id++;
        return id;
    }

    /**
     * 根据  uuid 获取建模数据id
     *
     * @param uuid
     * @return billid
     */
    public static int getBillidByUUID(String uuid, String tableName) {
        int billid = -1;
        RecordSet rs = new RecordSet();
        String sql = "select id from " + tableName + " where UUID = '" + uuid + "'";
        if (rs.execute(sql) && rs.next()) {
            billid = Util.getIntValue(rs.getString("id"));
        }
        log.info("根据  uuid 获取建模数据id    " + sql);
        return billid;
    }

}
